#include "ui_adminusermanage.h"
#include "adminusermanage.h"

AdminUserManage::AdminUserManage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AdminUserManage)
{
    ui->setupUi(this);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);  // 水平拉伸
    m_pSqliteManage = new SqliteManage;
    model = new UserModel(this,m_pSqliteManage->getDB());
    setupUI();
    loadData();
}

AdminUserManage::~AdminUserManage()
{
    delete ui;
    m_pSqliteManage->closeDatabase();

}

void AdminUserManage::setWidgetInfo(QString username)
{
    getUserInfo(username);  //得到用户的数据
    ui->labelUsername->setText(UserName);   //设置label数据
    ui->labelEmail->setText(email);
    ui->labelPhone->setText(phone);
    ui->labelNickname->setText(nickname);
    ui->labelRole->setText(user_role);
}

void AdminUserManage::getUserInfo(QString username)//得到用户的数据
{
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << m_pSqliteManage->lastError();
        //emit sendMessage("数据库连接错误");
        return;
    }
    QList<QVariantMap> users = m_pSqliteManage->selectData("users","name='" + username + "'");
    foreach (const QVariantMap &user, users) {
        UserName = user["name"].toString();
        PassWord = user["passwd"].toString();
        user_role = user["role"].toString();
        email = user["email"].toString();
        phone = user["phone"].toString();
        nickname = user["nickname"].toString();
    }
}

void AdminUserManage::setupUI()
{
    // 表格视图
    ui->tableView->setModel(model);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
    ui->tableView->verticalHeader()->hide();
    ui->tableView->resizeColumnsToContents();
    // 信号连接
    connect(ui->btnAdd, &QPushButton::clicked, this, &AdminUserManage::addUser);
    connect(ui->btnDelete, &QPushButton::clicked, this, &AdminUserManage::deleteUser);
    connect(ui->btnSave, &QPushButton::clicked, this, &AdminUserManage::saveChanges);
    connect(ui->btnRefresh, &QPushButton::clicked, this, &AdminUserManage::loadData);
}

void AdminUserManage::loadData()
{
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << m_pSqliteManage->lastError();
        //emit sendMessage("数据库连接错误");
        return;
    }
    model->setTable("users");
    model->select();
    ui->tableView->hideColumn(0); // 隐藏ID列
}

void AdminUserManage::addUser()
{
    QSqlRecord record = model->record();
    record.setValue("username", "new_user");
    record.setValue("password", QCryptographicHash::hash("123456", QCryptographicHash::Sha256).toHex());
    record.setValue("email", QString("user%1@example.com").arg(model->rowCount()+1));
    record.setValue("phone", QString("138%1").arg(QDateTime::currentSecsSinceEpoch() % 10000000));
    record.setValue("role", "user");

    if (model->insertRecord(-1, record)) {
        ui->tableView->scrollToBottom();
    }
}

void AdminUserManage::deleteUser() {
    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) return;

    if (QMessageBox::question(this, tr("确认"), tr("确定删除选中用户？")) == QMessageBox::Yes) {
        foreach (const QModelIndex &index, selected) {
            model->removeRow(index.row());
        }
    }
}

void AdminUserManage::saveChanges()
{
    if (!model->submitAll()) {
        QMessageBox::critical(this, tr("错误"),
            tr("保存失败：%1").arg(model->lastError().text()));
        model->revertAll();
    } else {
        QMessageBox::information(this, tr("成功"), tr("修改已保存！"));
    }
}

